package edu.gdpu.classloader;

import java.lang.reflect.Method;

/**
 * @author mazebin
 * @date 2021年 07月08日 15:53:10
 */
public class ClassLoaderTest21 {
    public static void main(String[] args)  throws Exception{
        CustomClassLoader loader1 = new CustomClassLoader("loader1");
        loader1.setPath("D:\\testClass\\");
        CustomClassLoader loader2 = new CustomClassLoader("loader2");
        loader2.setPath("D:\\testClass\\");
        Class<?> aClass = loader1.loadClass("edu.gdpu.classloader.Person");
        Class<?> aClass2  = loader2.loadClass("edu.gdpu.classloader.Person");
        //由于clazz1和clazz2分别有不同的类加载器所加载，所以他们处于不同的命名空间里
        System.out.println(aClass == aClass2);
        System.out.println(aClass.getClassLoader());
        System.out.println(aClass2.getClassLoader());
        Object o = aClass.newInstance();
        Object o1 = aClass2.newInstance();
        Method method = aClass.getMethod("setPerson",Object.class);
         //此处报错，loader1和loader2所处不用的命名空间
       method.invoke(o,o1);
        /**
         * 输出结果
         * findClass,输出这句话说明我们自己的类加载器加载了指定的类
         * findClass,输出这句话说明我们自己的类加载器加载了指定的类
         * false
         * edu.gdpu.classloader.CustomClassLoader@6d6f6e28
         * edu.gdpu.classloader.CustomClassLoader@45ee12a7
         * Exception in thread "main" java.lang.reflect.InvocationTargetException
         * 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         * 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
         * 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         * 	at java.lang.reflect.Method.invoke(Method.java:498)
         * 	at edu.gdpu.classloader.ClassLoaderTest21.main(ClassLoaderTest21.java:24)
         * Caused by: java.lang.ClassCastException: edu.gdpu.classloader.Person cannot be cast to edu.gdpu.classloader.Person
         * 	at edu.gdpu.classloader.Person.setPerson(Person.java:11)
         * 	... 5 more
         */

    }
}
